﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;

namespace Admin.NET.Application;

/// <summary>
/// 出库管理服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class OutboundmanageService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Outboundmanage> _outboundmanageRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public OutboundmanageService(SqlSugarRepository<Outboundmanage> outboundmanageRep, ISqlSugarClient sqlSugarClient)
    {
        _outboundmanageRep = outboundmanageRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询出库管理 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询出库管理")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<OutboundmanageOutput>> Page(PageOutboundmanageInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _outboundmanageRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.outboundmanageCode.Contains(input.Keyword) || u.consignee.Contains(input.Keyword) || u.Contact.Contains(input.Keyword) || u.remark.Contains(input.Keyword) || u.outbounddetails.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.outboundmanageCode), u => u.outboundmanageCode.Contains(input.outboundmanageCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.consignee), u => u.consignee.Contains(input.consignee.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Contact), u => u.Contact.Contains(input.Contact.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.remark), u => u.remark.Contains(input.remark.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.outbounddetails), u => u.outbounddetails.Contains(input.outbounddetails.Trim()))
            .WhereIF(input.outboundId != null, u => u.outboundId == input.outboundId)
            .WhereIF(input.warehouseId != null, u => u.warehouseId == input.warehouseId)
            .WhereIF(input.OutboundTimeRange?.Length == 2, u => u.OutboundTime >= input.OutboundTimeRange[0] && u.OutboundTime <= input.OutboundTimeRange[1])
            .WhereIF(input.saleId != null, u => u.saleId == input.saleId)
            .WhereIF(input.clientId != null, u => u.clientId == input.clientId)
            .WhereIF(input.AttnId != null, u => u.AttnId == input.AttnId)
            .WhereIF(input.outboundType != null, u => u.outboundType == input.outboundType)
            .WhereIF(input.OutboundQuantity != null, u => u.OutboundQuantity == input.OutboundQuantity)
            .LeftJoin<Outboundtype>((u, outbound) => u.outboundId == outbound.Id)
            .LeftJoin<Warehouse>((u, outbound, warehouse) => u.warehouseId == warehouse.Id)
            .LeftJoin<Commodityinformation>((u, outbound, warehouse, sale) => u.saleId == sale.Id)
            .LeftJoin<Customermanagement>((u, outbound, warehouse, sale, client) => u.clientId == client.Id)
            .LeftJoin<UserManagement>((u, outbound, warehouse, sale, client, attn) => u.AttnId == attn.Id)
            .Select((u, outbound, warehouse, sale, client, attn) => new OutboundmanageOutput
            {
                Id = u.Id,
                outboundmanageCode = u.outboundmanageCode,
                outboundId = u.outboundId,
                outboundFkDisplayName = $"{outbound.OutboundName}",
                warehouseId = u.warehouseId,
                warehouseFkDisplayName = $"{warehouse.WarehouseName}",
                OutboundTime = u.OutboundTime,
                saleId = u.saleId,
                saleFkDisplayName = $"{sale.ItemName}",
                clientId = u.clientId,
                clientFkDisplayName = $"{client.CustomerName}",
                consignee = u.consignee,
                Contact = u.Contact,
                AttnId = u.AttnId,
                AttnFkDisplayName = $"{attn.UserName}",
                remark = u.remark,
                outbounddetails = u.outbounddetails,
                outboundType = u.outboundType,
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                OutboundPrice = u.OutboundPrice,
                OutboundQuantity = u.OutboundQuantity,
                OutboundAmount = u.OutboundAmount,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取出库管理详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取出库管理详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Outboundmanage> Detail([FromQuery] QueryByIdOutboundmanageInput input)
    {
        return await _outboundmanageRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加出库管理 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加出库管理")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddOutboundmanageInput input)
    {
        var entity = input.Adapt<Outboundmanage>();
        return await _outboundmanageRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新出库管理 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新出库管理")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateOutboundmanageInput input)
    {
        var entity = input.Adapt<Outboundmanage>();
        await _outboundmanageRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除出库管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除出库管理")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteOutboundmanageInput input)
    {
        var entity = await _outboundmanageRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _outboundmanageRep.FakeDeleteAsync(entity);   //假删除
        //await _outboundmanageRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除出库管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除出库管理")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteOutboundmanageInput> input)
    {
        var exp = Expressionable.Create<Outboundmanage>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _outboundmanageRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _outboundmanageRep.FakeDeleteAsync(list);   //假删除
        //return await _outboundmanageRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataOutboundmanageInput input)
    {
        var outboundIdData = await _outboundmanageRep.Context.Queryable<Outboundtype>()
            .InnerJoinIF<Outboundmanage>(input.FromPage, (u, r) => u.Id == r.outboundId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.OutboundName}"
            }).ToListAsync();
        var warehouseIdData = await _outboundmanageRep.Context.Queryable<Warehouse>()
            .InnerJoinIF<Outboundmanage>(input.FromPage, (u, r) => u.Id == r.warehouseId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.WarehouseName}"
            }).ToListAsync();
        var saleIdData = await _outboundmanageRep.Context.Queryable<Commodityinformation>()
            .InnerJoinIF<Outboundmanage>(input.FromPage, (u, r) => u.Id == r.saleId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.ItemName}"
            }).ToListAsync();
        var clientIdData = await _outboundmanageRep.Context.Queryable<Customermanagement>()
            .InnerJoinIF<Outboundmanage>(input.FromPage, (u, r) => u.Id == r.clientId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.CustomerName}"
            }).ToListAsync();
        var attnIdData = await _outboundmanageRep.Context.Queryable<UserManagement>()
            .InnerJoinIF<Outboundmanage>(input.FromPage, (u, r) => u.Id == r.AttnId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "outboundId", outboundIdData },
            { "warehouseId", warehouseIdData },
            { "saleId", saleIdData },
            { "clientId", clientIdData },
            { "attnId", attnIdData },
        };
    }
    
    /// <summary>
    /// 导出出库管理记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出出库管理记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageOutboundmanageInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportOutboundmanageOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "出库管理导出记录");
    }
    
    /// <summary>
    /// 下载出库管理数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载出库管理数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportOutboundmanageOutput>(), "出库管理导入模板", (_, info) =>
        {
            if (nameof(ExportOutboundmanageOutput.outboundFkDisplayName) == info.Name) return _outboundmanageRep.Context.Queryable<Outboundtype>().Select(u => $"{u.OutboundName}").Distinct().ToList();
            if (nameof(ExportOutboundmanageOutput.warehouseFkDisplayName) == info.Name) return _outboundmanageRep.Context.Queryable<Warehouse>().Select(u => $"{u.WarehouseName}").Distinct().ToList();
            if (nameof(ExportOutboundmanageOutput.saleFkDisplayName) == info.Name) return _outboundmanageRep.Context.Queryable<Commodityinformation>().Select(u => $"{u.ItemName}").Distinct().ToList();
            if (nameof(ExportOutboundmanageOutput.clientFkDisplayName) == info.Name) return _outboundmanageRep.Context.Queryable<Customermanagement>().Select(u => $"{u.CustomerName}").Distinct().ToList();
            if (nameof(ExportOutboundmanageOutput.AttnFkDisplayName) == info.Name) return _outboundmanageRep.Context.Queryable<UserManagement>().Select(u => $"{u.UserName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入出库管理记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入出库管理记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportOutboundmanageInput, Outboundmanage>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 出库类型ID
                    var outboundIdLabelList = pageItems.Where(x => x.outboundFkDisplayName != null).Select(x => x.outboundFkDisplayName).Distinct().ToList();
                    if (outboundIdLabelList.Any()) {
                        var outboundIdLinkMap = _outboundmanageRep.Context.Queryable<Outboundtype>().Where(u => outboundIdLabelList.Contains($"{u.OutboundName}")).ToList().ToDictionary(u => $"{u.OutboundName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.outboundId = outboundIdLinkMap.GetValueOrDefault(e.outboundFkDisplayName ?? "");
                            if (e.outboundId == null) e.Error = "出库类型ID链接失败";
                        });
                    }
                    // 链接 仓库名称ID
                    var warehouseIdLabelList = pageItems.Where(x => x.warehouseFkDisplayName != null).Select(x => x.warehouseFkDisplayName).Distinct().ToList();
                    if (warehouseIdLabelList.Any()) {
                        var warehouseIdLinkMap = _outboundmanageRep.Context.Queryable<Warehouse>().Where(u => warehouseIdLabelList.Contains($"{u.WarehouseName}")).ToList().ToDictionary(u => $"{u.WarehouseName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.warehouseId = warehouseIdLinkMap.GetValueOrDefault(e.warehouseFkDisplayName ?? "");
                            if (e.warehouseId == null) e.Error = "仓库名称ID链接失败";
                        });
                    }
                    // 链接 关联单号
                    var saleIdLabelList = pageItems.Where(x => x.saleFkDisplayName != null).Select(x => x.saleFkDisplayName).Distinct().ToList();
                    if (saleIdLabelList.Any()) {
                        var saleIdLinkMap = _outboundmanageRep.Context.Queryable<Commodityinformation>().Where(u => saleIdLabelList.Contains($"{u.ItemName}")).ToList().ToDictionary(u => $"{u.ItemName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.saleId = saleIdLinkMap.GetValueOrDefault(e.saleFkDisplayName ?? "");
                            if (e.saleId == null) e.Error = "关联单号链接失败";
                        });
                    }
                    // 链接 客户名称
                    var clientIdLabelList = pageItems.Where(x => x.clientFkDisplayName != null).Select(x => x.clientFkDisplayName).Distinct().ToList();
                    if (clientIdLabelList.Any()) {
                        var clientIdLinkMap = _outboundmanageRep.Context.Queryable<Customermanagement>().Where(u => clientIdLabelList.Contains($"{u.CustomerName}")).ToList().ToDictionary(u => $"{u.CustomerName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.clientId = clientIdLinkMap.GetValueOrDefault(e.clientFkDisplayName ?? "");
                            if (e.clientId == null) e.Error = "客户名称链接失败";
                        });
                    }
                    // 链接 经办人
                    var attnIdLabelList = pageItems.Where(x => x.AttnFkDisplayName != null).Select(x => x.AttnFkDisplayName).Distinct().ToList();
                    if (attnIdLabelList.Any()) {
                        var attnIdLinkMap = _outboundmanageRep.Context.Queryable<UserManagement>().Where(u => attnIdLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.AttnId = attnIdLinkMap.GetValueOrDefault(e.AttnFkDisplayName ?? "");
                            if (e.AttnId == null) e.Error = "经办人链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.OutboundQuantity == null){
                            x.Error = "出库数量不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<Outboundmanage>>();
                    
                    var storageable = _outboundmanageRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.outboundmanageCode?.Length > 32, "出库单号长度不能超过32个字符")
                        .SplitError(it => it.Item.consignee?.Length > 32, "收货人长度不能超过32个字符")
                        .SplitError(it => it.Item.Contact?.Length > 32, "联系人长度不能超过32个字符")
                        .SplitError(it => it.Item.remark?.Length > 200, "备注长度不能超过200个字符")
                        .SplitError(it => it.Item.outbounddetails?.Length > 32, "出库明细长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
